package com.mavenq.fly.filter;

import com.mavenq.fly.utils.SqlExecuteContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
public class SqlStatsFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 开始请求前初始化上下文
        SqlExecuteContext.get();
        
        try {
            chain.doFilter(request, response);
        } finally {
            // 请求结束后获取统计信息并记录
            SqlExecuteContext.SqlExecuteStats stats = SqlExecuteContext.get();
            if (stats.getExecuteCount() > 0) {
                logStats(request, stats);
            }
            // 清除ThreadLocal
            SqlExecuteContext.reset();
        }
    }
    
    private void logStats(ServletRequest request, SqlExecuteContext.SqlExecuteStats stats) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestUri = httpRequest.getRequestURI();
        log.info("Request URI: {}, SDI拦截器执行次数: {}, 总执行时间: {}ms", requestUri, stats.getExecuteCount(), stats.getTotalTime());
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    
    @Override
    public void destroy() {}
}